/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package HTTPDownloader;

import java.util.ArrayList;

/**
 *
 * @author Lone_Wolf
 */
public class RangeManager {

    private long contentLength = 0;
    private int numWorkers = 0;
    private ArrayList<Range> remaining = new ArrayList<Range>();
    private ArrayList<Range> completed = new ArrayList<Range>();
    private ArrayList<Range> working = new ArrayList<Range>();

    public RangeManager() {
    }

    private void splitNormal() {
        for (int i = 0; i < numWorkers; i++) {
            working.add(new Range(i * contentLength / numWorkers,
                    (i + 1) * contentLength / numWorkers));
        }
    }

    public int getNumWorkers() {
        return numWorkers;
    }

    public void setNumWorkers(int numWorkers) {
        this.numWorkers = numWorkers;
    }

    public long getContentLength() {
        return contentLength;
    }

    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
    }

    public void addRemainingRange(Range r) {
        remaining.add(r);
        working.remove(r);
    }

    public void addWorkingRange(Range r) {
        working.add(r);
        remaining.remove(r);
    }

    public void addCompletedRange(Range r) {
        remaining.remove(r);
        working.remove(r);
        completed.add(r);
    }

    public boolean isRangeRemaining() {
        return !remaining.isEmpty();
    }

    public Range getFirstRemainingRange() {
        return remaining.get(0);
    }

    public long getCompletedSize() {
        long size = 0;
        for (int i = 0; i < completed.size(); i++) {
            size += completed.get(i).getDownloaded();
        }
        return size;
    }

    public ArrayList<Range> getCompletedRanges() {
        return completed;
    }

    public ArrayList<Range> getWorkingRanges() {
        return working;
    }

    public ArrayList<Range> getRemainingRanges() {
        return remaining;
    }

    public void setCompleted(ArrayList<Range> completed) {
        this.completed = completed;
    }

    public void setRemaining(ArrayList<Range> remaining) {
        this.remaining = remaining;
    }

    public long getTotalSizeDownloaded() {
        long total = 0;
        for (int i = 0; i < working.size(); i++) {
            total += working.get(i).getDownloaded();
        }
        total += getCompletedSize();
        return total;
    }

    public long getTotalSizeRemaining() {
        long total = 0;
        for (int i = 0; i < working.size(); i++) {
            total += working.get(i).getRemaining();
        }
        for (int i = 0; i < remaining.size(); i++){
            total += remaining.get(i).getLength();
        }
        return total;
    }
}
